package com.vitetest.api.config;

import com.vitetest.api.entity.User;
import com.vitetest.api.repository.UserRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

/**
 * 数据初始化器
 * 在应用启动时创建测试用户
 * 
 * @author ViteTest Team
 * @version 1.0.0
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class DataInitializer implements CommandLineRunner {

    private final UserRepository userRepository;
    private final PasswordEncoder passwordEncoder;

    @Override
    public void run(String... args) throws Exception {
        log.info("开始初始化测试数据...");
        
        // 创建测试用户
        createTestUsers();
        
        log.info("测试数据初始化完成！");
    }

    private void createTestUsers() {
        // 检查是否已存在测试用户
        if (userRepository.existsByUsername("admin")) {
            log.info("测试用户已存在，跳过初始化");
            return;
        }

        // 创建管理员用户
        User adminUser = new User();
        adminUser.setUsername("admin");
        adminUser.setPassword(passwordEncoder.encode("admin"));
        adminUser.setEmail("admin@vitetest.com");
        adminUser.setAvatar("https://images.unsplash.com/photo-1472099645785-5658abf4ff4e?w=150&h=150&fit=crop&crop=face");
        adminUser.setRole("ADMIN");
        adminUser.setEnabled(true);
        userRepository.save(adminUser);
        log.info("创建管理员用户: admin");

        // 创建普通用户
        User normalUser = new User();
        normalUser.setUsername("user");
        normalUser.setPassword(passwordEncoder.encode("user"));
        normalUser.setEmail("user@vitetest.com");
        normalUser.setAvatar("https://images.unsplash.com/photo-1494790108755-2616b612b786?w=150&h=150&fit=crop&crop=face");
        normalUser.setRole("USER");
        normalUser.setEnabled(true);
        userRepository.save(normalUser);
        log.info("创建普通用户: user");

        // 创建测试用户
        User testUser = new User();
        testUser.setUsername("test");
        testUser.setPassword(passwordEncoder.encode("test"));
        testUser.setEmail("test@vitetest.com");
        testUser.setAvatar("https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?w=150&h=150&fit=crop&crop=face");
        testUser.setRole("USER");
        testUser.setEnabled(true);
        userRepository.save(testUser);
        log.info("创建测试用户: test");
    }
} 